package com.cd2cd.code_template.configuration.security.jwt;

import java.util.Calendar;
import java.util.HashSet;
import java.util.Set;


import com.alibaba.fastjson.JSONObject;
import com.cd2cd.code_template.configuration.security.TokenUser;
import com.cd2cd.code_template.configuration.security.loginUserService.LoadUserService;
import com.cd2cd.code_template.configuration.security.loginUserService.LoadUserService.SysAdmin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.stereotype.Component;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.core.JsonProcessingException;

import javax.annotation.Resource;

@Slf4j
@Component
public class JwtUser {

	private static final String USER_INFO_KEY = "U_INFO";

	@Resource
	JwtProperties jwtProperties;

	public void setJwtProperties(JwtProperties jwtProperties) {
		this.jwtProperties = jwtProperties;
	}

	/**
	 * 生成token 设置： # 过期时间 # 用户标识 #
	 * */
	public String getToken(Object loginObj) throws JsonProcessingException {
		Algorithm algorithm = Algorithm.HMAC256(jwtProperties.getBase64Secret());

		Calendar expiresAt = Calendar.getInstance();
		expiresAt.add(Calendar.MINUTE, jwtProperties.getTokenValidityInMinute());
		String userStr = JSONObject.toJSONString(loginObj);

		String token = JWT.create()
				.withClaim(USER_INFO_KEY, userStr)
				.withExpiresAt(expiresAt.getTime())
				.sign(algorithm);

		return token;
	}

	public String getClaimByToken(String token) {
		Algorithm algorithm = Algorithm.HMAC256(jwtProperties.getBase64Secret());
		JWTVerifier verifier = JWT.require(algorithm).build(); // Reusable

		DecodedJWT jwt = verifier.verify(token);
		String userStr = jwt.getClaim(USER_INFO_KEY).asString();
		return userStr;
	}

	public static void main(String[] args) throws Exception {

		JwtProperties jwtProperties = new JwtProperties();
		jwtProperties.setHeader("Authorization");
		jwtProperties.setBase64Secret("code_template$lwl123789@hyl");
		jwtProperties.setTokenValidityInMinute(30);

		JwtUser jwtUser = new JwtUser();
		jwtUser.setJwtProperties(jwtProperties);

		Set<GrantedAuthority> set = new HashSet<GrantedAuthority>();
		set.add(new SimpleGrantedAuthority("role_addUser"));
		TokenUser tokenUser = new TokenUser(null,"13693227063", "-", SysAdmin.class, set);

		log.info("{}", tokenUser.getAuthIds());

		String token = jwtUser.getToken(tokenUser);
		String json = jwtUser.getClaimByToken(token);
		log.info("\ntoken={}, \njson={}", token, json);

		log.info("{}", SysAdmin.class.getSimpleName());


		Class<? extends LoadUserService.LoginTypeUser> type = SysAdmin.class;

		log.info("{}", type.getSimpleName());
	}

}
